/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.yixiang.co
* 注意：
* 本软件为www.yixiang.co开发研制，未经购买不得使用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package co.yixiang.modules.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.enums.AuctionOrderEnum;
import co.yixiang.modules.user.domain.YxAuthentication;
import co.yixiang.modules.user.domain.YxDistributorEarnings;
import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.modules.user.domain.YxUser;
import co.yixiang.modules.user.domain.YxUserBill;
import co.yixiang.modules.user.service.YxAuthenticationService;
import co.yixiang.modules.user.service.dto.DistributorDetail;
import co.yixiang.modules.user.service.dto.JuniorUserDataDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import co.yixiang.dozer.service.IGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import co.yixiang.common.utils.QueryHelpPlus;
import co.yixiang.utils.ValidationUtil;
import co.yixiang.utils.FileUtil;
import co.yixiang.modules.user.service.YxDistributorEarningsService;
import co.yixiang.modules.user.service.dto.YxDistributorEarningsDto;
import co.yixiang.modules.user.service.dto.YxDistributorEarningsQueryCriteria;
import co.yixiang.modules.user.service.mapper.YxDistributorEarningsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Pageable;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @author yhh
* @date 2020-09-16
*/
@Service
@AllArgsConstructor
//@CacheConfig(cacheNames = "yxDistributorEarnings")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class YxDistributorEarningsServiceImpl extends BaseServiceImpl<YxDistributorEarningsMapper, YxDistributorEarnings> implements YxDistributorEarningsService {

    private final IGenerator generator;
    private final YxAuthenticationService authenticationService;

    @Override
    //@Cacheable
    public Map<String, Object> queryAll(YxDistributorEarningsQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<YxDistributorEarningsDto> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), YxDistributorEarningsDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<YxDistributorEarningsDto> queryAll(YxDistributorEarningsQueryCriteria criteria){
//        return baseMapper.selectList(QueryHelpPlus.getPredicate(YxDistributorEarnings.class, criteria));
        return baseMapper.selectEarinDto(criteria);
    }


    @Override
    public void download(List<YxDistributorEarningsDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxDistributorEarningsDto yxDistributorEarnings : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户id", yxDistributorEarnings.getUid());
            map.put("订单id", yxDistributorEarnings.getOid());
            map.put("收益金额", yxDistributorEarnings.getPrice());
            map.put("1 - 有效  2 - 无效 ", yxDistributorEarnings.getStatus());
            map.put("创建时间", yxDistributorEarnings.getCreateTime());
            map.put("是否已收0否1是", yxDistributorEarnings.getIsOver());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 获取用户首页信息
     *
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> index(YxUser user , int page , int limit) {

        Map<String, Object> IndexData = new HashMap();
        IndexData.put("userEarning" , baseMapper.getUserPrice(user.getUid()));

        Page<JuniorUserDataDTO> pageModel = new Page<>(page, limit);
        IPage<JuniorUserDataDTO> pageList = baseMapper.getJuniorData(pageModel , user.getUid());
        for (JuniorUserDataDTO juniorUserDataDTO: pageList.getRecords()) {

            //查看用户是否实名
            if(ObjectUtil.isNotEmpty(getUserName(juniorUserDataDTO.getUid()))) juniorUserDataDTO.setNickname(getUserName(juniorUserDataDTO.getUid()));

            BigDecimal b1 = BigDecimal.ZERO;

            //获取二级对我造成的收益
            b1 = b1.add(baseMapper.getOneDownPrice(user.getUid(), juniorUserDataDTO.getUid()));
            //获取三级通过二级对我造成的收益
            b1 = b1.add(baseMapper.getDownPrice(user.getUid() , juniorUserDataDTO.getUid()));

            juniorUserDataDTO.setBrokeragePrice(b1);

        }
        IndexData.put("juniorUserData" , pageList);

        return IndexData;
    }

    /**
     * 获取佣金明细
     *
     * @param user
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Map<String, Object> detail(YxUser user, int page, int limit) {

        Map<String , Object> detail = new HashMap<>();
        detail.put("price" , baseMapper.getPriceByType(user.getUid() , AuctionOrderEnum.IS_OVER_1.getValue()));
        Page<DistributorDetail> pageModel = new Page<>(page, limit);

        IPage<DistributorDetail> distributorDetail = baseMapper.getDistributorDetail(pageModel, user.getUid(), AuctionOrderEnum.IS_OVER_1.getValue());
        distributorDetail.getRecords().forEach(distributorDetail1 -> {
            //查看用户是否实名
            if(ObjectUtil.isNotEmpty(getUserName(distributorDetail1.getUid()))) distributorDetail1.setNickname(getUserName(distributorDetail1.getUid()));
        });

        detail.put("distributorDetail" , distributorDetail);
        return detail;
    }

    /**
     * 他人佣金明细
     *
     * @param user
     * @param otherUid
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Map<String, Object> otherDetail(YxUser user, Long otherUid, int page, int limit) {

        Map<String , Object> otherDetail = new HashMap<>();
        JuniorUserDataDTO juniorUserData = baseMapper.getJuniorDataByUid(otherUid);
        if(ObjectUtil.isNotEmpty(getUserName(juniorUserData.getUid()))) juniorUserData.setNickname(getUserName(juniorUserData.getUid()));
        BigDecimal b1 = BigDecimal.ZERO;
        //获取二级对我造成的收益
        b1 = b1.add(baseMapper.getOneDownPrice(user.getUid(), juniorUserData.getUid()));
        //获取三级通过二级对我造成的收益
        b1 = b1.add(baseMapper.getDownPrice(user.getUid() , juniorUserData.getUid()));
        juniorUserData.setBrokeragePrice(b1);
        otherDetail.put("juniorUserData", juniorUserData);

        Page<DistributorDetail> pageModel = new Page<>(page, limit);
        IPage<DistributorDetail> distributorDetail = baseMapper.getOtherDistributorDetail(pageModel, user.getUid(),otherUid);
        distributorDetail.getRecords().forEach(distributorDetail1 -> {
            if(ObjectUtil.isNotEmpty(getUserName(distributorDetail1.getUid()))) distributorDetail1.setNickname(getUserName(distributorDetail1.getUid()));
        });
        otherDetail.put("distributorDetail" , distributorDetail);
        return otherDetail;
    }

    //查看用户是否实名
    private String getUserName(Long uid){
        YxAuthentication authentication = authenticationService.getOne(new QueryWrapper<YxAuthentication>().lambda()
                .eq(YxAuthentication::getUid, uid)
                .eq(YxAuthentication::getStatus, "1"));
        if (ObjectUtil.isNotEmpty(authentication)) return authentication.getRealName();

        return null;
    }
}
